package captcha_mw

import (
	"MoSkeleton/config/consts"
	"MoSkeleton/config/properties"
	"MoSkeleton/framework"
	fc "MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/dto/response"
	"MoSkeleton/global"
	"MoSkeleton/services"
	"MoSkeleton/web/pogos/request/public"
	"context"
	"github.com/gin-gonic/gin"
	"github.com/samber/lo"
	"time"
)

func DoCheckCaptcha() gin.HandlerFunc {
	return func(c *gin.Context) {
		captchaProperty := &global.ConfigContainerInst.AppConfig.App.Captcha
		if !captchaProperty.Enable {
			c.Next()
			return
		}
		model, exists := c.Get(fc.GinContext_Model_Key)
		if !exists {
			response.ErrorParam(c, "param invalidate")
			return
		}
		loginReq := model.(public.LoginReq)
		processCaptchaCheck(c, captchaProperty, &loginReq)
	}
}

func processCaptchaCheck(c *gin.Context, captchaProperty *properties.CaptchaProperty, loginReq *public.LoginReq) {
	if lo.IsEmpty[string](loginReq.Uuid) {
		response.ErrorParam(c, "uuid")
		return
	}
	strCmd := framework.MoRedis.Get(context.Background(), consts.RedisKey_Captcha_Id+loginReq.Uuid)
	if strCmd.Err() != nil || strCmd.Val() == "" {
		response.FailMsg(c, fc.CaptchaCheckFailCode, "验证码已过期")
		return
	}
	framework.MoRedis.Del(context.Background(), consts.RedisKey_Captcha_Id+loginReq.Uuid)
	historyTime, err := strCmd.Int64()
	if err != nil {
		response.FailMsg(c, fc.CaptchaCheckFailCode, "验证码已过期")
		return
	}
	if time.Now().Unix()-historyTime > int64(time.Duration(captchaProperty.TimeOut)*time.Second) {
		response.FailMsg(c, fc.CaptchaCheckFailCode, "验证码已过期")
		return
	}
	ok := services.ServiceGroupInst.PublicGroupInst.CaptchaServiceInst.VerifyCaptcha(loginReq)
	if !ok {
		response.FailMsg(c, fc.CaptchaCheckParamsInvalidCode, "验证码错误")
		return
	}
	c.Next()
}
